package cn.chongqing.han.toolkit;

import android.text.Editable;
import android.util.Base64;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

    public static final String CHARSET_UTF_8 = "utf-8";
    public final static String ENCODING = "UTF-8";
    public final static int LOW_HEAP_SIZE = 48;
    public final static int HIGH_HEAP_SIZE = 96;

    public static boolean isObjNull(Object obj) {
        return obj == null;
    }

    public static boolean isObjNotNull(Object obj) {
        return obj != null;
    }

    public static boolean isNotBlank(String str) {
        boolean b = isBlank(str);
        return !b;
    }

    public static boolean isNotBlank(Editable editable) {
        boolean b = isBlank(editable);
        return !b;
    }

    public static boolean isBlank(Editable editable) {
        if (editable == null)
            return true;
        return isBlank(editable.toString());
    }

    public static boolean isBlank(String str) {
        if (str == null)
            return true;
        if (str.equals("") || str.trim().equals(""))
            return true;

        return false;
    }

    public static String toUTF8URLEncodeStr(String jsonStr)
            throws UnsupportedEncodingException {
        String result = URLEncoder.encode(jsonStr, CHARSET_UTF_8);
        return result;
    }

    public static String getBitMapUrl(String url) {
        String[] arrayUrl = url.split("\\.");
        if (arrayUrl.length < 2) {
            return "";
        }
        arrayUrl[arrayUrl.length - 2] = arrayUrl[arrayUrl.length - 2];
        return Arrays.toString(arrayUrl).replaceAll(", ", ".")
                .replaceAll("\\[", "").replaceAll("]", "");
    }


    public static String getBitMapUrlM(String url) {
        String[] arrayUrl = url.split("\\.");
        if (arrayUrl.length < 2) {
            return "";
        }
        arrayUrl[arrayUrl.length - 2] = arrayUrl[arrayUrl.length - 2] + "-M";
        return Arrays.toString(arrayUrl).replaceAll(", ", ".")
                .replaceAll("\\[", "").replaceAll("]", "");
    }

    public static String getBitMapUrlL(String url) {
        String[] arrayUrl = url.split("\\.");
        if (arrayUrl.length < 2) {
            return "";
        }
        arrayUrl[arrayUrl.length - 2] = arrayUrl[arrayUrl.length - 2] + "-L";
        return Arrays.toString(arrayUrl).replaceAll(", ", ".")
                .replaceAll("\\[", "").replaceAll("]", "");
    }

    public static String getBitMapUrlS(String url) {
        String[] arrayUrl = url.split("\\.");
        if (arrayUrl.length < 2) {
            return "";
        }
        arrayUrl[arrayUrl.length - 2] = arrayUrl[arrayUrl.length - 2] + "-S";
        return Arrays.toString(arrayUrl).replaceAll(", ", ".")
                .replaceAll("\\[", "").replaceAll("]", "");
    }

    // 加密
    public static String encoded(String data)
            throws UnsupportedEncodingException {
        return Base64.encodeToString(data.getBytes(CHARSET_UTF_8),
                Base64.DEFAULT);
    }

    // 解密
    public static String decode(String data)
            throws UnsupportedEncodingException {
        byte[] b = Base64.decode(data.getBytes(CHARSET_UTF_8), Base64.DEFAULT);
        return new String(b);
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    // 判断手机格式是否正确
    public static boolean isMobilePhone(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isTelephone(String telNO) {
        String regx = "(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{8}";
        Pattern pt = Pattern.compile(regx);
        return pt.matcher(telNO).matches();
    }

    public static boolean isAvailableContact(String contact) {
        return isMobilePhone(contact) || isTelephone(contact);
    }

    // 判断email格式是否正确
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static boolean checkPwdValid(String pwd) {
        if (pwd == null || pwd.equals(""))
            return false;
        if (pwd.length() < 6)
            return false;

        return true;
    }

    public static Float formatFloat(Float f) {
        if (f == null)
            return 0f;

        DecimalFormat df = new DecimalFormat("#");
        return Float.valueOf(df.format(f));
    }

    /**
     * 保留2位销小数
     */
    public static Float formatFloat2(Float f) {
        if (f == null)
            return 0f;

        DecimalFormat df = new DecimalFormat("#.00");
        return Float.valueOf(df.format(f));
    }

    public static Float formatFloat2(Double f) {
        if (f == null)
            return 0f;

        DecimalFormat df = new DecimalFormat("#.00");
        return Float.valueOf(df.format(f));
    }

    public static String formatPhoneNumber(String phoneNum) {
        String result;
        if (phoneNum.contains(";")) {
            result = phoneNum.replace(";", ",");
        } else {
            result = phoneNum;
        }
        String[] list = result.split(",");
        if (list.length == 1) {
            return result;
        }
        StringBuffer formatedResult = new StringBuffer();
        Hashtable<String, String> table = new Hashtable<String, String>();
        for (int i = 0; i < list.length; i++) {
            table.put(list[i], list[i]);
        }
        Iterator<String> iterator = table.keySet().iterator();
        while (iterator.hasNext()) {
            formatedResult.append(iterator.next());
            if (iterator.hasNext()) {
                formatedResult.append(",");
            }
        }
        return formatedResult.toString();
    }

    public static String getEditText(EditText editText) {
        if (editText == null || editText.getText() == null || editText.getText().toString().equals(""))
            return "";
        else
            return editText.getText().toString();
    }

    public static String getTimeStamp() {
        return System.currentTimeMillis() + "";
    }

    public static String mapToAppUserName(String username) {
        return "";
        /*if(username!=null && username.indexOf("_")>0) {
            String appUserId = username.split("_")[0];
			if(appUserId!=null)
			{
				Map<String,UserInfo> userInfos = AppApplication.getInstance().getUserInfosMap();
				if(userInfos!=null){
					UserInfo u = userInfos.get(appUserId);
					if(u!=null){
						username = u.getRealName();
					}
				}
			}
		}
		return username;*/
    }

    public static String subStr(String content, int size) {
        if (StringUtil.isBlank(content))
            return "";
        else {
            if (content.length() <= size)
                return content;
            else
                return content.substring(0, 20);
        }
    }


    public static boolean isJson(String jsonStr) {
        if (isBlank(jsonStr))
            return false;
        try {
            new JSONObject(jsonStr);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isJson(String jsonStr, Class clz) {
        if (!isBlank(jsonStr)) {
            try {
                new Gson().fromJson(jsonStr, clz);
                return true;
            } catch (JsonSyntaxException e) {
            }
        }
        return false;
    }

    /**
     * 给Url加入参数
     *
     * @param url
     * @return
     */
    public static String addParams(String url, String key, String value) {
        if (url.contains("?"))
            url = url + "&" + key + "=" + value;
        else
            url = url + "?" + key + "=" + value;

        return url;
    }


}
